var {
  get,
  post,
  getWidthHeder,
  postWithHeader,
} = require('./../../comm/localHttp');

var {
  encryptByMd5
} = require('./../../comm/commHelper')

var app = getApp();

Page({

  data: {
    showHospitalFlag: true,
    userId: '',
    password: '',
    selectedDepartment: null,
    selectedHospital: null,
    departmentList: [],
    hospitalList: [],
    canLogin: false,
    weChatId: ''
  },
  onLoad: async function () {
    console.log('load');
    wx.login({
      success: async (loginRes) => {
        app.globalData.wechatCode = loginRes.code;
        console.log('登录 ok:' + loginRes.code);
        const res = await getWidthHeder('/hospital/id', {
          wechatCode: loginRes.code
        }, 'hospital');
        console.log('res...', res);
        if (res.code != 0) {
          wx.showModal({
            title: '错误!',
            content: '获取医院信息异常! code: ' + res.code + res.msg
          })
          return;
        }
        console.log('获取医院信息', res);
        // app.globalData.hospitalId = res.data.hospitalId;
        let hospital = {};
        let listHospital = res.data.hospital;
        if (listHospital && listHospital.length > 0) {
          hospital = listHospital[res.data.hospital.length - 1];
        }
        app.globalData.wechatCode = res.data.openId;
        this.setData({
          hospitalList: listHospital,
          selectedHospital: hospital
        });
        this.updateHospital();
      }
    });
  },

  onUserIdInput: function (e) {
    const userId = e.detail.value;
    this.setData({
      userId: e.detail.value
    });
    this.requestDepartmentData(userId);
    this.checkCanLogin();
  },


  onDepartmentChange: function (e) {
    const index = e.detail.value;
    const selectedDepartment = this.data.departmentList[index];
    this.setData({
      selectedDepartment: selectedDepartment
    });
    this.checkCanLogin();
  },

  onHospitalChange: function (e) {
    const index = e.detail.value;
    const selHosptial = this.data.hospitalList[index];
    this.setData({
      selectedHospital: selHosptial
    });
    this.updateHospital();
    this.checkCanLogin();
  },

  updateHospital: function (e) {
    if (this.data.selectedHospital) {
      app.globalData.hospitalId = this.data.selectedHospital.hospitalId;
    }
  },

  onPasswordInput: function (e) {
    this.setData({
      password: e.detail.value
    });
    this.checkCanLogin();
  },
  click_add_hospital: function (e) {
    wx.showModal({
      editable: true, //显示输入框
      placeholderText: '请输入医院码', //显示输入框提示信息
      success: res => {
        if (res.confirm) { //点击了确认
          console.log(res.content) //用户输入的值
          //添加到列表,并切换到
          const hospitalId = res.content;
          let hospitalList = this.data.hospitalList;
          const addHospital = {
            hospitalId: hospitalId,
            hospitalName: hospitalId
          }
          hospitalList.push({
            hospitalId: hospitalId,
            hospitalName: hospitalId
          });
          this.setData({
            hospitalList: hospitalList,
            selectedHospital: addHospital
          });
          this.updateHospital();
          this.checkCanLogin();
        } else {
          console.log('用户点击了取消')
        }
      }
    })
  },

  requestDepartmentData: async function (userId) {

    // 向后台请求部门数据的逻辑
    // 请求成功后将部门数据更新到data的departmentList中
    var departmentList = []; // replace with actual department data
    var selectedDepartment = {};
    const res = await get('/login/id_office', {
      id: userId
    });
    console.log('获取到的数据：', res);
    if (res.code == 0) {
      departmentList = res.data;
      if (departmentList.length > 0) {
        selectedDepartment = departmentList[0];
      }
    }
    this.setData({
      departmentList: res.data,
      selectedDepartment: selectedDepartment
    });
  },

  checkCanLogin: function () {
    const {
      selectedHospital,
      userId,
      selectedDepartment,
      password
    } = this.data;
    const canLogin = selectedHospital && userId && selectedDepartment && password;
    this.setData({
      canLogin: canLogin
    });
  },

  onLogin: async function () {
    var userId = this.data.userId;
    var officeCode = this.data.selectedDepartment.officeCode;
    var password = this.data.password;
    const res = await postWithHeader('/login/entry', {
      userId: userId,
      password: encryptByMd5(password)
    }, 'login');
    console.log('登录的数据', res);
    if (res.code == 0) {
      wx.setStorageSync('userInfo', {
        userId: userId,
        officeCode: officeCode,
        token: res.data.token,
      });
      // 向后台请求登录的逻辑
      // 请求成功后跳转到index页面
      wx.navigateTo({
        url: '/pages/index/index'
      });
    } else {
      wx.showModal({
        title: '错误',
        content: 'code:' + res.code + ';msg:' + res.msg
      });
    }
  }
});